import React, { useEffect, useState } from 'react';
import { Modal, View, Text, TouchableOpacity, StyleSheet, Image, TouchableWithoutFeedback } from 'react-native';
import { useDispatch } from 'react-redux';
import { subtractDiamonds } from '@/store/paymentSlice';
import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store'
import { addGiftReward } from '@/store/giftRewardSlice';



interface Gift {
    id: string;
    name: string;
    price: number;
    image: any;
}

interface GiftDetailModalProps {
    visible: boolean;
    gift: Gift | null; // 当前选中的礼物
    onClose: () => void; // 关闭模态框的回调
    onReward: (gift: Gift) => void; // 点击打赏时的回调
}

const GiftDetailModal: React.FC<GiftDetailModalProps> = ({ visible, gift, onClose, onReward }) => {
    if (!gift) return null;
    const dispatch = useDispatch();
    const router = useRouter();
    const [diamondCount, setdiamondCount] = useState<number | null>(0);
    useEffect(() => {
        const loaddia = async () => {
            try {
                const diamondCount = await SecureStore.getItemAsync('diamondCount');
                if (diamondCount) {
                    setdiamondCount(parseInt(diamondCount));
                }
            } catch (error) {
                console.error('Error loading diamond count:', error);
            }
        }
        loaddia();
    }, [diamondCount])
    const buttonTitle = diamondCount >= gift.price ? '打赏' : '去充值';
    const handleRewardButtonPress = async () => {
        if (diamondCount >= gift.price) {
            onReward(gift);

            // 获取当前时间
            const currentTime = new Date().toISOString(); // 获取当前时间戳，作为唯一标识

            // 创建新的打赏记录
            const giftRewardRecord = {
                id: currentTime, // 使用时间戳作为唯一标识
                time: currentTime,
                diamonds: gift.price, // 使用礼物的价格作为打赏的钻石数量
                giftName: gift.name, // 礼物名称
                giftImage: gift.image, // 礼物图片
            };
            console.log(giftRewardRecord, 'giftRewardRecord');
            

            // 添加打赏记录到 Redux
            await dispatch(addGiftReward(giftRewardRecord));

            // 更新钻石数量
            const newDiamondCount = diamondCount - gift.price;
            await dispatch(subtractDiamonds(gift.price));

            await SecureStore.setItemAsync('diamondCount', newDiamondCount.toString()); // 更新钻石数量
            setdiamondCount(newDiamondCount); // 更新本地状态

            onClose();
        } else {
            router.push('/my/diamond'); // 跳转到充值页面
        }
    };
    return (
        <Modal
            animationType="fade"
            transparent={true}
            visible={visible}
            onRequestClose={onClose}
        >
            <TouchableWithoutFeedback onPress={onClose}>
                <View style={styles.modalOverlay}>
                    <TouchableWithoutFeedback>
                        <View style={styles.modalContent}>
                            <Image source={gift.image} style={styles.giftImage} />
                            <Text style={styles.giftName}>{gift.name}</Text>
                            <Text style={styles.giftPrice}>{gift.price} 💎</Text>
                            <Text style={styles.yuePrice}>余额:{diamondCount}💎</Text>
                            <TouchableOpacity
                                style={styles.rewardButton}
                                onPress={handleRewardButtonPress}
                            >
                                <Text style={styles.rewardButtonText}>{buttonTitle}</Text>
                            </TouchableOpacity>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
            </TouchableWithoutFeedback>
        </Modal>
    );
};

const styles = StyleSheet.create({
    yuePrice: {
        fontSize: 10,
        color: 'white',
        textAlign: 'center',
        marginBottom: 10,
    },
    modalOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalContent: {
        backgroundColor: 'rgb(100, 100, 100)',
        borderRadius: 10,
        padding: 20,
        alignItems: 'center',
        width: 300,
    },
    giftImage: {
        width: 100,
        height: 100,
        marginBottom: 15,
    },
    giftName: {
        color: 'white',
        fontSize: 18,
        marginBottom: 10,
    },
    giftPrice: {
        color: 'white',
        fontSize: 14,
        marginBottom: 10,
    },
    rewardButton: {
        backgroundColor: 'rgb(104, 202, 252)',
        borderRadius: 5,
        width: 100,
        alignItems: 'center',
        marginBottom: 10,
        height: 30,
    },
    rewardButtonText: {
        color: 'white',
        fontSize: 16,
        textAlign: 'center',
        marginTop: 3,
    },
});

export default GiftDetailModal;
